package com.wandian.texas.entity;

import com.wandian.util.ArrayList;
import com.wandian.util.RandomUtil;

import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import com.wandian.executor.TimerCommand;
import com.wandian.texas.BaseCommandObject;
import com.wandian.texas.CalculateCard;
import com.wandian.texas.GameData;
import com.wandian.texas.GamePool;
import com.wandian.texas.GameServer;
import com.wandian.texas.SessionObject;
import com.wandian.texas.ThreadPool;
import com.wandian.texas.dao.Impl.GameRoomDaoImpl;
import com.wandian.texas.db.DBMgr;
import com.wandian.texas.protocol.Protocol;
import com.wandian.util.Log;
import com.wandian.xml.RoomConfigItem;

/**
 * @author long
 * @Create 2012-10-27 下午4:06:49
 * @QQ 108232706
 * @version 1.0
 * @description GameRoomEntity
 */
/**
 * @author long
 * @date 2013-1-9 下午5:15:53
 * @qq 108232706
 * @description GameRoomEntity
 */
public class GameRoomEntity extends DataObject {
	public int GameId;
	public int ServerId;
	public String errorStatus;
	public int RoomId;
	public int RoomCode;
	public String RoomName = "";
	public int PlayerNum;// 座位上游戏的玩家数
	public int SeatCount;// 坐位数，3~9
	// public int seatPlayerNum;// 坐位上人数
	public int totalNum;// 房间总人数
	public boolean isPlaying;
	// <----CMD_OPERATION_NEXT
	/**
	 * 当前最后下注玩家的坐位id
	 */
	public int curSeatId;
	public float minCall;
	public float minRaise;
	public float maxRaise;
	/**
	 * 上一个玩家为止,本轮的单人下注
	 */
	public float stake;
	public int step;
	public int SendStep;
	public int AccepStep;
	public int fold;
	/**
	 * 最大加注者(如果收到操作请求,处理完之后,判断下一个seat是不是最大者,若是则翻牌操作,
	 * ,第1回{大盲下一个->大盲(Raiser)}，初始是大盲
	 * (第一回给大盲最少一次操作机会,若大盲的callChip=MaxBind,则给操作,否则翻牌))
	 * 第2回{庄家下一个【小盲(Raiser)】->庄家,如果操作到了第2回的最大加注者结束(),转牌}
	 * 第3回{庄家下一个【小盲(Raiser)】->庄家,如果操作到了第3回的最大加注者结束(),河牌}
	 * 第4回{庄家下一个【小盲(Raiser)】->庄家,如果操作到了第4回的最大加注者结束(), Game_Over} 起始者可以顺时针推
	 */
	public int maxRaiseSeatId;

	public void resetMaxRaiseSeat() {
		if (this.userSeatsLen < 1)
			return;
		this.curSeatId = this.DealerId;
		int temp = this.MinBindSeatId;
		if (gameOverUsers[temp - 1].user != null && gameOverUsers[temp - 1].lastAction != LastAction.FOLD && gameOverUsers[temp - 1].lastAction != LastAction.ALLIN) {
			this.maxRaiseSeatId = temp;
			return;
		}
		int fn = 0;
		while (true) {
			temp = this.getNextSeat(temp);
			fn++;
			if (gameOverUsers[temp - 1].user != null && gameOverUsers[temp - 1].lastAction != LastAction.FOLD && gameOverUsers[temp - 1].lastAction != LastAction.ALLIN) {
				this.maxRaiseSeatId = temp;
				break;
			}
			if (fn >= 10) {
				throw new IllegalArgumentException("resetMaxRaiseSeat not find error!");
			}
		}

	}

	public SNAPCARDS snapCards;
	// --->
	public int prevId;
	public int NextId;
	public int GameState;// 0未开始,1，正在开始,2游戏结束
	public String[] PublicCard = new String[] { "-", "-", "-", "-", "-" };
	public String PublicAllCard = "";
	private int DealerId;
	public float MinBind;
	public int MinBindSeatId;
	public int MinBindUserId;
	public int MaxBindSeatId;
	public float MaxBind;
	public int MaxBindUserId;
	public int DlayTime;
	public float MinStake;
	public float MaxStake;
	public float NewChip;
	public String NewUserIds = "";
	public String WatchUserIds;
	public int StartChips;
	public TimerCommand timer;
	public boolean boolCanncel;
	public boolean doingGameOver;
	//	public void doingGameOver() {
	//		this.gameOverUsers.clear();
	//		if (this.gameUsers.size() < 1) {
	//			throw new IllegalArgumentException("游戏结束,gameUsers没有人" + this.RoomCode);
	//		}
	//		UserInfoEntity u;
	//		for (int i = 0; i < this.gameUsers.size(); i++) {
	//			u = this.gameUsers.get(i);
	//			gameOverUsers.add(u);
	//			u.gameOverSeatId = u.seatId;
	//		}
	//	}

	public int currPublicCardLen;
	public final ReentrantLock GameSeatLock = new ReentrantLock();
	public final ReentrantLock RoomDoorLock = new ReentrantLock();
	public final ReentrantLock InOutRoomLock = new ReentrantLock();

	/**
	 * 每把结束都要计算牌型，相同时间只会计算一个座位,防止new数据,保存在游戏中
	 */
	public final int[] fourAKingIndex = new int[4];

	/**
	 * 每次取getFourAkind之前先清空
	 */
	public void clearFourAKingIndex() {
		for (int i = 0; i < fourAKingIndex.length; i++) {
			fourAKingIndex[i] = -1;
		}
	}

	/**
	 * 对于5+2+1个牌，是否是结果牌的状态标志
	 */
	public final boolean[] boolWinCards = new boolean[8];

	/**
	 * 在选4,3,2牌的时候，会把相同结果置放在同index不同维度的牌组里,如boolFullHouse[0][0]
	 * boolFullHouse[0][1].4个都是true,说明出现4个同样，或三个
	 */
	public final int[] boolFullHouse = new int[8];
	/**
	 * 每种牌，4张相同，3相同的组数
	 */
	public final int[] sameNum = new int[4];
	/**
	 * 四组牌里A牌的索引,如1张 AIndex[0]
	 */
	public final int[] AIndex = new int[4];

	public final void clearFullHouse() {
		for (int i = 0; i < boolFullHouse.length; i++) {
			boolFullHouse[i] = 0;
		}
		for (int i = 0; i < AIndex.length; i++) {
			AIndex[i] = -1;
		}
	}

	/**
	 * 0列是全部牌，1-4四种花色，五列的指针
	 */
	public final int[] arrHuaseLen = new int[5];

	/**
	 * 全部牌长度保留,其他的为了临时使用，经常赋值，需要改变position
	 */
	public final void clearHuaseLen() {
		for (int i = 1; i < 5; i++) {
			arrHuaseLen[i] = 0;
		}
	}

	public CardVo[][] arrHuase = new CardVo[5][8];

	public void clearAllArrHuaseInfo() {
		//清除牌内容值
		for (int i = 0; i < arrHuase.length; i++) {
			for (int j = 0; j < arrHuase[i].length; j++) {
				arrHuase[i][j].num = 0;
			}
		}
		//清除总牌长度
		arrHuaseLen[0] = 0;
		//清除牌长度指针
		clearHuaseLen();
		//清除3,2,1牌组合的指针
		clearFullHouse();
	}

	public GameRoomEntity() {
		this.DlayTime = 15;
		timer = new TimerCommand("DelayMessageCmd", Protocol.CHATROOM_DELAY_MESSAGE, this.DlayTime, TimeUnit.SECONDS);

		for (int i = 0; i < 9; i++) {
			//			seatBonusMap.put(i, new java.util.ArrayList<UserInfoEntity>());
			gameOverUsers[i] = new UserGameEntity(this);
			gameOverUsers[i].seatId = i + 1;
			//			winnerMap.put(i, new java.util.ArrayList<UserGameEntity>());
		}

		//初始化卡牌内容值
		for (int i = 0; i < arrHuase.length; i++) {
			for (int j = 0; j < arrHuase[i].length; j++) {
				arrHuase[i][j] = new CardVo();
			}
		}

		//初始化一副扑克
		int k = 0;
		for (int i = 0; i < GamePool.pokervalues.length; i++) {
			k = i * 4;
			pokers[k] = GamePool.pokervalues[i] + PokerColor.CLUB.value();
			pokers[k + 1] = GamePool.pokervalues[i] + PokerColor.DIAMOND.value();
			pokers[k + 2] = GamePool.pokervalues[i] + PokerColor.HEART.value();
			pokers[k + 3] = GamePool.pokervalues[i] + PokerColor.SPADE.value();
		}
	}

	// 随机发牌
	public String[] pokers = new String[13 * 4];

	/**
	 * 保存一把游戏对应牌的索引下标，公共牌，0~4
	 * 1号,1+4,1+4+9;类推
	 */
	public int[] publicAndSeatPokerIndex = new int[5 + 18];
	/**
	 * 上一局产生的积宝牌
	 */
	public int[] lastPokers = new int[5 + 18];

	/**
	 * 根据扑克牌索引值取到公共牌
	 */
	public void setPublicCard() {
		for (int i = 0; i < 5; i++) {
			this.PublicCard[i] = pokers[publicAndSeatPokerIndex[i]];
		}
	}

	public void replacePoker(int seatId, int cardNum) {
		if (seatId > 0 & seatId < 10) {
			if (cardNum == 1 || cardNum == 2) {
				//以前的索引下标,基本上是被扔弃了
//				int oldCardIndex = getSeatPokerIndex(seatId, cardNum);
				int randomIndex = -1;
				int fn = 0;
				while (true) {
					fn++;
					randomIndex = RandomUtil.next(pokers.length);
					if (!CalculateCard.contains(publicAndSeatPokerIndex, randomIndex))
						break;
					if (fn > 100)
						throw new IllegalArgumentException("replacePoker error");
				}
				setSeatPokerIndex(seatId, cardNum, randomIndex);
			}
		}
	}

	public void setSeatPokerIndex(int seatId, int cardNum, int newIndex) {
		if (seatId > 0 & seatId < 10) {
			if (cardNum == 1) {
				publicAndSeatPokerIndex[seatId + 4] = newIndex;
				;
			} else if (cardNum == 2) {
				publicAndSeatPokerIndex[seatId + 13] = newIndex;
			}
		}
	}

	public int getSeatPokerIndex(int seatId, int cardNum) {
		if (seatId > 0 & seatId < 10) {
			if (cardNum == 1) {
				return publicAndSeatPokerIndex[seatId + 4];
			} else if (cardNum == 2) {
				return publicAndSeatPokerIndex[seatId + 13];
			}
		}
		return -1;
	}

	public String getSeatPoker(int seatId, int cardNum) {
		if (seatId > 0 & seatId < 10) {
			if (cardNum == 1) {
				return pokers[publicAndSeatPokerIndex[seatId + 4]];
			} else if (cardNum == 2) {
				return pokers[publicAndSeatPokerIndex[seatId + 13]];
			}
		}
		return "";
	}

	/**
	 * 随机洗牌
	 */
	public void shuffle() {
//		int fn;
		int randomIndex;
		for (int i = 0; i < publicAndSeatPokerIndex.length; i++) {
//			fn = 0;
			while (true) {
				randomIndex = RandomUtil.next(pokers.length);
//				fn++;
				if (!CalculateCard.contains(publicAndSeatPokerIndex, randomIndex, 0, i))
					break;
			}
			publicAndSeatPokerIndex[i] = randomIndex;
		}
	}

	public void useLastPoker() {
		for (int i = 0; i < publicAndSeatPokerIndex.length; i++) {
			publicAndSeatPokerIndex[i] = lastPokers[i];
		}
	}

	public void saveLastPoker() {
		for (int i = 0; i < publicAndSeatPokerIndex.length; i++) {
			lastPokers[i] = publicAndSeatPokerIndex[i];
		}
	}

	/**
	 * 只是为了统一请求操作与定时器操作，共用cmdObject的dataPacket,至于用户信息缓存另外一个字典
	 * 
	 * @param cmdObject
	 */
	public void startTimer(int type, int roomId, BaseCommandObject cmdObject, UserInfoEntity user) {
		timer.put("Type", type);
		timer.put("BaseCommandObject", cmdObject);
		timer.put("UserInfoEntity", user);
		timer.put("RoomId", roomId);
		boolCanncel = false;
		this.cancel();
		ThreadPool.getInstance().Push(timer);
		boolCanncel = false;
	}

	public void startTimer(int type, RoomConfigItem room, BaseCommandObject cmdObject) {
		timer.put("Type", type);
		timer.put("BaseCommandObject", cmdObject);
		timer.put("RoomConfigItem", room);
		boolCanncel = false;
		this.cancel();
		ThreadPool.getInstance().Push(timer);
		boolCanncel = false;
	}

	public void startTimer(int type) {
		timer.put("Type", type);
		boolCanncel = false;
		this.cancel();
		ThreadPool.getInstance().Push(timer);
		boolCanncel = false;
	}

	public void putTimerParams(String key, Object value) {
		timer.put(key, value);
	}

	public void delay(long delay) {
		this.timer.initialDelay = delay;
	}

	public void delay(long delay, TimeUnit _unit) {
		this.timer.delay(delay, _unit);
	}

	public boolean cancel() {
		boolean boolSuc = ThreadPool.getInstance().cancel(timer);
		boolCanncel = true;
		// Log.debug("移除任务:" + timer.name + (boolSuc ? "成功" : "失败"));
		return boolSuc;
	}

	/**
	 * 倒计时剩余时间
	 */
	int leftTime;
	public String stepMemo;

	public int getLeftTime() {
		leftTime = timer.getLeftTime();
		return leftTime;
	}

	/**
	 * 当前step下注
	 */
	public float giveChip;
	// public int[] SeatUserId = new int[9];
	// <---seatUsers
	public SessionObject[] seatUsers = new SessionObject[9];
	public java.util.ArrayList<SessionObject> roomUsers = new java.util.ArrayList<SessionObject>();
	/**
	 * 为了操作游戏设计
	 */
	public ArrayList<UserInfoEntity> gameUsers = new ArrayList<UserInfoEntity>();
	/**
	 * 防止游戏刚结束，还没有算出账，玩家就离开了，造成很多索引异常,
	 */
	public UserGameEntity[] gameOverUsers = new UserGameEntity[9];
	public boolean lastLeaveGameOver;
	public ArrayList<SessionObject> gameSessions = new ArrayList<SessionObject>();

	//最大下注筹码的seatid与stake
	public int maxStakeSeat;
	public float maxStake;

	public void setMaxStake() {
		if (!this.isPlaying || this.doingGameOver)
			return;
		if (this.foldCount >= this.gameOverLen - 1)
			return;
		maxStakeSeat = 0;
		maxStake = 0;
		UserGameEntity user;
		for (int i = 0; i < this.userSeatsLen; i++) {
			user = gameOverUsers[this.userSeats[i] - 1];
			if (user.user == null || user.lastAction == LastAction.FOLD)
				continue;
			if ((user.user.stake + user.seatChip) > maxStake) {
				this.maxStakeSeat = user.seatId;
				this.maxStake = user.user.stake + user.seatChip;
			}
		}
		/*for (int i = 1; i <= 9; i++) {
			if (this.userSeats[i] < 1)
				continue;
			user = gameOverUsers[i - 1];
			if (user.user == null || user.lastAction == LastAction.FOLD)
				continue;
			if ((user.user.stake + user.seatChip) > maxStake) {
				this.maxStakeSeat = i;
				this.maxStake = user.user.stake + user.seatChip;
			}
		}*/
		if (maxStakeSeat == 0)
			throw new IllegalArgumentException("setMaxStake error");
	}

	public float getSecondStake() {
		float sencondStake = 0;
		UserGameEntity user;
		for (int i = 0; i < this.userSeatsLen; i++) {
//			if (this.userSeats[i] < 1)
//				continue;
			user = gameOverUsers[this.userSeats[i] - 1];
			if (user.user == null || user.lastAction == LastAction.FOLD || user.seatId == this.maxStakeSeat)//最大筹码者不能下自己那么多筹码
				continue;
			if ((user.user.stake + user.seatChip) > sencondStake) {
				sencondStake = user.user.stake + user.seatChip;
			}
		}
		if (sencondStake == 0)
			throw new IllegalArgumentException("sencondStake error,maxStakeSeat:" + maxStakeSeat + " curseat:" + this.curSeatId + " gameid:" + this.GameId + " step:" + this.step + " userlen:" + this.userSeatsLen + ",gameoverlen:" + this.gameOverLen);
		return sencondStake;
	}

	public void printGameDetail() {
		StringBuilder sb = new StringBuilder("roomid:" + this.RoomId + " gameid:" + this.GameId);
		sb.append("============userSeatsLen:" + this.userSeatsLen + "\r\n[");
		for (int i = 1; i <= 9; i++) {
			if (this.userSeats[i] > 0)
				sb.append(i + ",");
		}
		sb.append("]=============================gameoveruser\r\n");
		UserGameEntity user;
		for (int i = 0; i < 9; i++) {
			user = this.gameOverUsers[i];
			if (user.user != null)
				sb.append(user.seatId + "," + user.user.userName + " lastaction:" + user.lastAction + "|");
		}
	}

	/**
	 * 每个回合结束之后，清除玩家操作的次数
	 */
	public void clearUserStep() {
		for (int i = 0; i < 9; i++) {
			gameOverUsers[i].step = 0;
		}
	}

	/**
	 * playing的时候到doingGameOver,不包括notplaying
	 * 
	 * @param session
	 */
	public void standUp(SessionObject session, int dbIndex) {
		UserGameEntity user = gameOverUsers[session.getUser().seatId - 1];
		/*int seatId;
		this.foldCount = 0;
		for (int i = 0; i < this.gameOverLen; i++) {
			seatId = this.gameOverSeats[i];
			if (gameOverUsers[seatId - 1].lastAction == LastAction.FOLD)
				this.foldCount++;
		}*/
		if (gameSessions.contains(session)) {
			if (this.foldCount < this.gameOverLen - 1) {
				if (user.lastAction != LastAction.FOLD) {
					if (user.lastAction == LastAction.ALLIN) {
						this.allinCount--;
					}
					this.foldCount++;
					user.lastAction = LastAction.FOLD;
					//站起，step日志，放弃
					user.user.lastAction = LastAction.FOLD;
					GamePool.gameRoomDao(dbIndex).addGameLog(this, this.GameId, 0, user.user, this.snapCards.value(), 0, 0, this.curSeatChip(user.seatId), this.curSeatTotalChip(user.seatId), "站起，放弃");
				}
			} else {
//				System.out.println("over");
			}
		}
		gameSessions.remove(session);
		gameUsers.remove(session.getUser());
		//保证最后一个离开的人,
//		if (gameUsers.size() > 0) {
//			gameOverUsers[session.getUser().seatId - 1].lastAction = LastAction.FOLD;
//		} else {
//			gameOverUsers[session.getUser().seatId - 1].lastAction = 0;
//		}
	}

	public boolean containGameUser(UserInfoEntity user) {
		return this.gameUsers.contains(user);
	}

	//	public boolean contain9SeatUser(SessionObject session) {
	//		for (SessionObject s : seatUsers) {
	//			if (s == session)
	//				return true;
	//		}
	//		return false;
	//	}

	public boolean containUserSeat(int seatId) {
		return CalculateCard.contains(this.userSeats, this.userSeatsLen, seatId);
//		return this.userSeats[seatId] > 0;
	}

	public boolean containWaitSeat(Integer seatId) {
		return this.waitSeats[seatId] > 0;
	}

	public boolean isNewGame = false;
	public boolean boolShowCard = false;

	public int foldCount;
	public int allinCount;

	public boolean isGameOver() {
		//保证每场游戏在执行结束后，就不会被其他线程再次做结束
		if (this.doingGameOver)
			return false;
		if (this.gameUsers.size() <= 1) {
			return true;
		}
		if (foldCount >= this.gameOverLen - 1) {
			boolShowCard = false;
			return true;
		}
		boolShowCard = true;
		if (foldCount + allinCount < this.gameOverLen - 1)
			return false;
		if (foldCount + allinCount >= this.gameOverLen)
			return true;
		if (this.maxRaiseSeatId != this.curSeatId) {
			return true;
		} else {
			return false;
		}
		//maxRaiseSeat->curSeat,走过，剩下的判断有没有可以出牌的
		/*int waitOperate = 0;
		UserGameEntity user;
		if (this.maxRaiseSeatId > this.curSeatId) {
			for (int i = this.curSeatId + 1; i < this.maxRaiseSeatId - 1; i++) {
				user = gameOverUsers[i - 1];
				if (user.user != null && user.lastAction != LastAction.FOLD)
					waitOperate++;
			}
		} else if (this.maxRaiseSeatId < this.curSeatId) {
			for (int i = 1; i < this.maxRaiseSeatId - 1; i++) {
				user = gameOverUsers[i - 1];
				if (user.user != null && user.lastAction != LastAction.FOLD && user.lastAction != LastAction.ALLIN)
					waitOperate++;
			}
			for (int i = this.curSeatId + 1; i <= 9; i++) {
				user = gameOverUsers[i - 1];
				if (user.user != null && user.lastAction != LastAction.FOLD && user.lastAction != LastAction.ALLIN)
					waitOperate++;
			}
		} else {
			//当前人下更大的注,说明之前肯定有玩家是非放弃，非allin
			waitOperate = 1;
		}
		if (waitOperate > 0) {
			return false;
		} else {
			boolShowCard = true;
			return true;
		}*/
	}

	public boolean isGameOver0() {
		//保证每场游戏在执行结束后，就不会被其他线程再次做结束
		if (this.doingGameOver)
			return false;
		if (this.gameUsers.size() < 1) {
			return true;
		}
		boolShowCard = false;
		int canOperateCount = 0;
		int waitShowCount = 0;
		int flodCount = 0;
		// boolean isStepOver = true;
		//		UserInfoEntity curUser = null;// = this.getUser(this.curSeatId);
		UserInfoEntity user;
		for (int i = 0; i < this.gameUsers.size(); i++) {
			user = this.gameUsers.get(i);
			if (user.lastAction != LastAction.FOLD) {
				waitShowCount++;
			} else {
				flodCount++;
			}
			if (user.lastAction == LastAction.FOLD || user.lastAction == LastAction.ALLIN) {
				continue;
			}
			//			curUser = user;
			canOperateCount++;
		}
		boolShowCard = waitShowCount > 1;
		//		Log.debug("游戏可操作的人数,:" + canOperateCount);
		if (canOperateCount == 1) {
			UserInfoEntity maxuser = this.getUser(this.maxRaiseSeatId);
			if (maxuser.stake <= 0) {
				// 当前最大加注
				if (this.maxRaiseSeatId == this.curSeatId) {
					return false;
				}
				UserInfoEntity nextUser = null;
				int tempSeatId = this.curSeatId;
				int find = 0;
				while (true) {
					find++;
					if (find > 10) {
						Log.error("什么破代码,找了9个座位都找不到合适的出牌的人");
						break;
					}
					nextUser = getNextUser(tempSeatId);
					// 弃牌，全压的跳过
					if (!this.containGameUser(nextUser) || nextUser.lastAction == LastAction.FOLD || nextUser.lastAction == LastAction.ALLIN) {
						tempSeatId = nextUser.seatId;
						nextUser = null;
						continue;
					} else {
						break;
					}
				}
				if (nextUser.seatId <= this.curSeatId || nextUser.seatId >= this.maxRaiseSeatId) {
					return true;
				} else {
					return false;
				}
				// if (this.maxRaiseSeatId != this.curSeatId && nextUser.seatId
				// == this.maxRaiseSeatId)
				// return true;
			} else {
				return true;
			}
		}
		if (canOperateCount == 0) {
			return true;
		}

		if (flodCount >= gameUsers.size() - 1) {
			boolShowCard = false;
			return true;
		}
		return false;
	}

	//	public boolean FlodGameOver(int seatId) {
	//		if (this.gameUsers.size() < 1) {
	//			return true;
	//		}
	//		boolShowCard = false;
	//		boolean isStepOver = true;
	//		int canOperateCount = 0;
	//		int waitShowCount = 0;
	//		UserInfoEntity user;
	//		for (int i = 0; i < this.gameUsers.size(); i++) {
	//			user = this.gameUsers.get(i);
	//			if (user.lastAction != LastAction.FOLD) {
	//				waitShowCount++;
	//			}
	//			if (user.lastAction == LastAction.FOLD || user.lastAction == LastAction.ALLIN) {
	//				continue;
	//			}
	//			if (user.seatId > seatId || user.seatId < this.maxRaiseSeatId) {
	//				isStepOver = false;
	//			}
	//			canOperateCount++;
	//		}
	//		boolShowCard = waitShowCount > 1;
	//		Log.debug("游戏可操作的人数,:" + canOperateCount);
	//		if (canOperateCount <= 1 && isStepOver)
	//			return true;
	//		return false;
	//	}

	//	public boolean allInGameOver(int seatId) {
	//		if (this.gameUsers.size() < 1) {
	//			return true;
	//		}
	//		boolShowCard = false;
	//		int canOperateCount = 0;
	//		int waitShowCount = 0;
	//		boolean allStep = true;
	//		UserInfoEntity user;
	//		for (int i = 0; i < this.gameUsers.size(); i++) {
	//			user = this.gameUsers.get(i);
	//			if (user.lastAction != LastAction.FOLD) {
	//				waitShowCount++;
	//			}
	//			if (user.lastAction == LastAction.FOLD || user.lastAction == LastAction.ALLIN) {
	//				continue;
	//			}
	//			if (user.step == 0) {
	//				allStep = false;
	//			}
	//			canOperateCount++;
	//		}
	//		boolShowCard = waitShowCount > 1;
	//		Log.debug("游戏可操作的人数,:" + canOperateCount);
	//		if (canOperateCount < 2 && allStep)
	//			return true;
	//		return false;
	//	}

	/**
	 * 根据坐位找session
	 * 
	 * @param seatId
	 * @return
	 */
	public SessionObject seatUsers(int seatId) {
		if (seatId > 0 && seatId < 10) {
			return seatUsers[seatId - 1];
		}
		return null;
	}

	/**
	 * 根据坐位找session
	 * 
	 * @param seatId
	 * @return
	 */
	public UserInfoEntity getUser(int seatId) {
		if (seatId > 0 && seatId < 10) {
			if (seatUsers[seatId - 1] == null)
				return null;
			return seatUsers[seatId - 1].getUser();
		}
		return null;
	}

	/**
	 * 新回合开始，桌上chip清空，以及lastaction
	 */
	public void clearCallChip() {
		// Iterator<Integer> it = userSeats.iterator();
		// int tempSeatId;
		// UserInfoEntity user;
		// int tempMax;
		// while (it.hasNext()) {
		// tempSeatId = it.next();
		// user = getUser(tempSeatId);
		// // user.clear();
		// }
	}

	public void beforStartGame() {
		// 将两组用户合并
		//		userSeats.addAll(waitSeats);
		for (int i = this.waitSeatsLen - 1; i >= 0; i--) {
			userSeats[userSeatsLen++] = waitSeats[i];
			this.waitSeatsLen--;
		}
		this.foldCount = 0;
		this.allinCount = 0;
	}

	public int allSeatUserCount() {
		return this.userSeatsLen + this.waitSeatsLen;
	}

	public void reset() {
		this.fold = 0;
		this.step = 0;
		this.AccepStep = 0;
		this.curSeatId = 0;
		// 座位上人状恢复
		// Iterator<Integer> it=userSeats.iterator();
		// UserInfoEntity user;
		// while(it.hasNext()){
		// user=this.getUser(it.next());
		// user.lastAction=0;
		// user.callChip(0);
		// }
		if (allSeatUserCount() < 2) {
			isNewGame = true;
		} else {
			isNewGame = false;
		}
		UserInfoEntity user;
		for (int i = 0; i < this.roomUsers.size(); i++) {
			user = this.roomUsers.get(i).getUser();
			user.lastAction = 0;
			user.totalChip = 0;
			user.card1 = "-";
			user.card2 = "-";
			user.isWin = 0;
			user.state = GameData.WAIT_NEXT_GAME;
			//			for (int j = 0; j < user.bonusWin.length; j++) {
			//				user.bonusWin[j] = 0;
			//			}
		}
		this.stake = 0;
		this.curBonusIndex = 0;
		this.currPublicCardLen = 0;
		for (int i = 0; i < this.BonusPools.length; i++) {
			this.BonusPools[i] = 0;
		}
		this.clearSeatChip();
		// 清除奖池与用户的映射关系
		allWinnersLen = 0;
		for (int i = 0; i < 9; i++) {
			//			seatBonusMap.get(i).clear();
			gameOverUsers[i].clear();
			winnerMapLen[i] = 0;
			allWinners[i] = null;
			for (int j = 0; j < 9; j++) {
				winnerMap[i][j] = null;
			}
			//			winnerMap.get(i).clear();
		}
		//		winnerMap.clear();
		//		allWinners.clear();
		//		this.clearSeatTotalChip();
		//		this.clearSeatTotalWinChip();
		this.gameUsers.clear();
		this.gameSessions.clear();
		lastLeaveGameOver = false;
		this.PublicAllCard = "";
		for (int i = 0; i < 5; i++) {
			this.PublicCard[i] = "-";
		}
	}

	/**
	 * 新回合开始，设置起始者 小盲开始
	 */
	public void resetMaxRaiser() {
		if (userSeatsLen < 1)
			return;
		int tempMaxRaiseSeatId = this.getNextSeat(this.MaxBindSeatId);
		// int tempMaxRaiseSeatId = this.MaxBindSeatId;
		int find = 0;
		UserInfoEntity user;
		while (true) {
			user = getUser(tempMaxRaiseSeatId);
			find++;
			if (find > 10) {
				Log.error("什么破程序，找了9次都未找到起始者");
				break;
			}
			// 取下一个
			if (user == null || user.lastAction == LastAction.FOLD) {
				tempMaxRaiseSeatId = this.getNextSeat(tempMaxRaiseSeatId);
			} else {
				// 若玩家在，且没有放弃,从他开始出牌,
				this.maxRaiseSeatId = user.seatId;
				// this.curSeatId = user.seatId;
				break;
			}
		}
	}

	public int resetStandMaxRaiser() {
		if (this.foldCount >= this.gameOverLen - 1)
			return this.maxRaiseSeatId;
		int tempSeatId = this.maxRaiseSeatId;
		UserGameEntity user = null;
		int fn = 0;
		while (true) {
			fn++;
			try {
				tempSeatId = this.getNextSeat(tempSeatId);
				user = gameOverUsers[tempSeatId - 1];
			} catch (Exception e) {
				Log.error(e);
			}
			if (user.user != null && user.lastAction != LastAction.FOLD && user.lastAction != LastAction.ALLIN) {
				break;
			}
			if (fn >= 10) {
				throw new IllegalArgumentException("resetStandMaxRaiser error");
			}
		}
		if (this.maxRaiseSeatId == tempSeatId) {
			throw new IllegalArgumentException("resetStandMaxRaiser error ,not the one");
		}
		this.maxRaiseSeatId = tempSeatId;
		return this.maxRaiseSeatId;
	}

	public int resetStandMaxRaiser0() {
		int tempSeatId = this.maxRaiseSeatId;
		//		Log.debug("准备找当前最大MaxRaiser找之前：" + tempSeatId);
		UserInfoEntity nextUser = null;
		int find = 0;
		while (true) {
			find++;
			if (find > 10) {
				Log.error("什么破代码,找了9个座位都找不到合适的出牌的人,gameid:" + this.GameId);
				break;
			}
			nextUser = this.getNextUser(tempSeatId);
			// 弃牌，全压的跳过
			if (!containGameUser(nextUser) || nextUser.lastAction == LastAction.FOLD || nextUser.lastAction == LastAction.ALLIN) {
				tempSeatId = nextUser.seatId;
				nextUser = null;
				continue;
			} else {
				break;
			}
		}
		if (nextUser == null) {
			return 0;
			// throw new IllegalArgumentException(
			// "when operate maxRaiseSeatId invalid,find count:" + find);
		}
		this.maxRaiseSeatId = nextUser.seatId;
		//		Log.debug("准备找当前最大MaxRaiser找之后：" + tempSeatId);
		return this.maxRaiseSeatId;
	}

	// seatUsers--->
	// <----userSeats
	public int[] userSeats = new int[9];// 玩家坐位数组,升序[4,8]
	public int[] gameOverSeats = new int[9];
	public byte userSeatsLen = 0;
	public byte gameOverLen = 0;
	public byte waitSeatsLen = 0;
	public int[] waitSeats = new int[9];// 玩家坐位数组,升序[4,8]
//	public java.util.ArrayList<Integer> waitSeats = new java.util.ArrayList<Integer>();

	public void clearGameOverSeats() {
		for (int i = 0; i < gameOverSeats.length; i++) {
			gameOverSeats[i] = 0;
		}
	}

	/**
	 * 当前坐位自动下移,并返回最新的坐位[0,1,2,....]
	 * 
	 * @return
	 */
	public int nextSeat() {
		if (userSeatsLen < 1)
			return 0;
		int index = CalculateCard.indexOf(this.userSeats, userSeatsLen, this.curSeatId);
		if (index == -1) {
			this.curSeatId = this.userSeats[0];
		}
		index++;
		if (index >= userSeatsLen)
			index = 0;
		this.curSeatId = this.userSeats[index];
		return this.curSeatId;
		/*int preSeatId = this.curSeatId;
		//		int fn = 0;
		while (true) {
			this.curSeatId++;
		//			fn++;
			if (this.curSeatId > 9)
				this.curSeatId = 1;
			if (userSeats[this.curSeatId] > 0) {
				break;
			}
		//			if (fn > 10)
		//				throw new IllegalArgumentException("userSeats 全部不大于0");
		}
		if (preSeatId == this.curSeatId) {
			Log.error("nextSeat找了一圈找回原来的坐位");
		}
		return this.curSeatId;*/
	}

	/**
	 * 只取下一个坐位，游标没有变化
	 * 
	 * @return
	 */
	public int getNextSeat() {
		return getNextSeat(this.curSeatId);
	}

//	public int nextIndex;
	/**
	 * 根据上一个坐位找下一个坐位，游标没有变化
	 * 
	 * @return
	 */
	public int getNextSeat(int preSeatId) {
		if (userSeatsLen < 1)
			return 0;
		int index = CalculateCard.indexOf(this.userSeats, userSeatsLen, preSeatId);
		if (index == -1) {
			return this.userSeats[0];
		}
		index++;
		if (index > userSeatsLen - 1)
			index = 0;
		return this.userSeats[index];
		/*int nextSeatId = preSeatId;
		while (true) {
			nextSeatId++;
			if (nextSeatId > 9)
				nextSeatId = 1;
			if (userSeats[nextSeatId] > 0) {
				break;
			}
		}
		if (nextSeatId == preSeatId) {
			Log.error("nextSeat找了一圈找回原来的坐位");
		}
		return nextSeatId;*/
	}

	/**
	 * 当前坐位自动下移,并返回最新的session
	 * 
	 * @return
	 * */
	public SessionObject nextSession() {
		return seatUsers(nextSeat());
	}

	/**
	 * 只取下一个坐位的session，游标没有变化
	 * 
	 * @return
	 * */
	public SessionObject getNextSession() {
		return seatUsers(getNextSeat());
	}

	/**
	 * 当前坐位自动下移,并返回最新的user
	 * 
	 * @return
	 * */
	public UserInfoEntity nextUser() {
		return getUser(nextSeat());
	}

	/**
	 * 只取下一个坐位的user，游标没有变化
	 * 
	 * @return
	 * */
	public UserInfoEntity getNextUser() {
		return getUser(getNextSeat());
	}

	/**
	 * 只取下一个坐位的user，游标没有变化
	 * 
	 * @return
	 * */
	public UserInfoEntity getNextUser(int preSeatId) {
		return getUser(getNextSeat(preSeatId));
	}

	// userSeats----->

	// <--------Chip,Stake
	/*public float getMaxRaiseStake0(int seatId) {
		float maxRaiseTo = 0;
		Iterator<Integer> it = userSeats.iterator();
		int tempSeatId;
		UserInfoEntity user;
		float tempMax;
		while (it.hasNext()) {
			tempSeatId = it.next();
			// 如果是自己,跳过
			if (tempSeatId == seatId)
				continue;
			user = getUser(tempSeatId);
			if (user.lastAction != LastAction.FOLD) {
				tempMax = user.stake + this.callChip(user.seatId);
				if (tempMax > maxRaiseTo) {
					maxRaiseTo = tempMax;
				}
			}
		}
		return maxRaiseTo;
	}*/
	public float maxRaiseTo;
//	public float getMaxRaiseStake(int seatId) {
//		float maxRaiseTo = 0;
//		int tempSeatId;
//		UserInfoEntity user;
//		float tempMax;
//		for (int i = 0; i < this.userSeats.size(); i++) {
//			tempSeatId = this.userSeats.get(i);
//			// 如果是自己,跳过
//			if (tempSeatId == seatId)
//				continue;
//			user = getUser(tempSeatId);
//			if (user.lastAction != LastAction.FOLD) {
//				tempMax = user.stake + this.callChip(user.seatId);
//				if (tempMax > maxRaiseTo) {
//					maxRaiseTo = tempMax;
//				}
//			}
//		}
//		return maxRaiseTo;
//	}

	// Chip,Stake----------->
	// public String[] HandCard = new String[] { "-", "-" };
	// public int[] FanpaiCallChip = new int[9];
	// public int[] ZhuanpaiCallChip = new int[9];
	// public int[] HepaiCallChip = new int[9];
	public float[] BonusPools = new float[9];// 所有玩家的边池总和如{9*100,8*100,7*100}
	public float[] SystemWinPools = new float[9];// 系统抽成
	public java.util.ArrayList<CornucopiaEntity> Cornucopias = new java.util.ArrayList<CornucopiaEntity>();
//	public CornucopiaEntity Cornucopias = new java.util.ArrayList<CornucopiaEntity>();
	/**
	 * 调用积宝存储过程成功标志位，游戏开始也置false
	 */
	public boolean addCornucopiaSuc;

	public String getBonusPools() {
		String BonusPoolsInfo = "";
		for (int i = 0; i < BonusPools.length; i++) {
			if (BonusPools[i] > 0) {
				if (i == 0) {
					BonusPoolsInfo += BonusPools[i];
				} else {
					BonusPoolsInfo += "|" + BonusPools[i];
				}
			} else {
				break;
			}
		}
		return BonusPoolsInfo;
	}

	/**
	 * 边池与玩家映射关系
	 */
	//	public Map<Integer, java.util.ArrayList<UserInfoEntity>> seatBonusMap = new HashMap<Integer, java.util.ArrayList<UserInfoEntity>>();
	//	public float[] seatChips = new float[9];// 玩家桌上下注数组
	//	public float[] seatTotalChips = new float[9];
	/**
	 * 每局，每个座位赢的钱 (减去座位上总的钱，就是赢的可+可-)
	 */
	//	public float[] seatTotalWinChips = new float[9];

	public float curSeatChip(int seatId) {
		if (seatId > 0 && seatId < 10) {
			return gameOverUsers[seatId - 1].seatChip;
		}
		return 0;
	}

	public float curSeatTotalChip(int seatId) {
		if (seatId > 0 && seatId < 10) {
			return gameOverUsers[seatId - 1].totalBet;
		}
		return 0;
	}

	public int curBonusIndex = 0;

	/**
	 * 玩家加注增加
	 * 
	 * @param SeatId
	 * @param addChip
	 */
	public void callChip(int SeatId, float addChip) {
		try {
			UserInfoEntity user = gameOverUsers[SeatId - 1].user;
			if (user.stake < addChip) {
				throw new IllegalArgumentException("callChip stake error!game:" + this.GameId + ",user:" + user.userId + " stake:" + user.stake + " addChip:" + addChip + " lastAction:" + user.lastAction + " user room:" + user.roomId);
			}
			gameOverUsers[SeatId - 1].seatChip += addChip;
			gameOverUsers[SeatId - 1].totalBet += addChip;

			// Log.debug(String.format("玩家%s下注%s ,之前筹码%s", user.nickName, addChip,
			// user.stake));
			user.stake -= addChip;
			if (user.stake <= 0) {
//				user.stake = 0;
				user.lastAction = LastAction.ALLIN;
				gameOverUsers[SeatId - 1].lastAction = LastAction.ALLIN;
			} else {
				if (gameOverUsers[SeatId - 1].seatChip > stake) {
					stake = gameOverUsers[SeatId - 1].seatChip;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.error(e);
		}
		// Log.debug("下注后为:" + user.stake);

	}

	/**
	 * 下注增加到
	 * 
	 * @param SeatId
	 * @param callChip
	 */
	//	public void callChipTo(int SeatId, int callChip) {
	//		seatChips[SeatId - 1] = callChip;
	//	}

	/**
	 * 返回该回合坐位下的总额
	 * 
	 * @param SeatId
	 * @return
	 */
	public float callChip(int SeatId) {
		if (SeatId > 0 && SeatId < 10) {
			return gameOverUsers[SeatId - 1].seatChip;
		} else {
			return 0;
		}

	}

	/**
	 * 每一回合开始,桌上下注清空
	 */
	public void clearSeatChip() {
		for (int i = 0; i < 9; i++) {
			//			seatChips[i] = 0;
			gameOverUsers[i].seatChip = 0;
		}
	}

	public UserGameEntity[] seatChipList = new UserGameEntity[9];
	public int SeatChipLen;

	/**
	 * 桌上下注的钱入池
	 */
	public void InBonusPool() {
		int seatId;
		UserGameEntity user;
		SeatChipLen = 0;
		for (int i = 0; i < curBonusIndex + 1; i++) {
			this.BonusPools[i] = 0;
		}
		curBonusIndex = 0;
		for (int i = 0; i < this.gameOverLen; i++) {
			seatId = this.gameOverSeats[i];
			user = gameOverUsers[seatId - 1];
			if (user.totalBet > 0) {
				//如果在如池，玩家已经离开，
				seatChipList[SeatChipLen++] = user;
			}
		}
		//排序大-小
		CalculateCard.sortSeatChip(this);
		float chip;
		int size;
		float allin = 0;
		float singleTotal = 0;
		UserGameEntity curSeatChip;
		while (SeatChipLen > 0) {
			float baseChip = seatChipList[SeatChipLen - 1].totalBet - singleTotal;
			singleTotal += baseChip;
			size = SeatChipLen;
			allin = 0;
			for (int i = 0; i < size; i++) {
				curSeatChip = seatChipList[i];
				chip = curSeatChip.totalBet;
				chip = chip - singleTotal;
				this.BonusPools[this.curBonusIndex] += baseChip;
//				putBonus(curBonusIndex, curSeatChip.seatId);
				curSeatChip.bonusIndex = this.curBonusIndex;
				// 最后一个边池出现allin,下次计算要从新的边池开始
				if (chip == 0 && curSeatChip.lastAction == LastAction.ALLIN) {
					if (allin != curSeatChip.totalBet) {
						allin = curSeatChip.totalBet;
					}
				}
				if (chip == 0) {
					SeatChipLen--;
					// Log.debug("移除了减为0的一项，当前长度:" + seatChipList.size());
				}
			}
			//			Log.debug("第边" + (curBonusIndex + 1) + "池形成,总额:" + this.BonusPools[curBonusIndex] + " 当前桌上筹码长度:" + seatChipList.size());
			if (allin > 0) {
				curBonusIndex++;
			}
		}
		/*StringBuilder sb = new StringBuilder("奖池已形成:");
		for (int i = 1; i <= this.BonusPools.length; i++) {
			if (this.BonusPools[i - 1] <= 0) {
				break;
			}
			sb.append(i + ":" + this.BonusPools[i - 1] + " ;");
		}
		Log.info(sb.toString());*/
	}

	/**
	 * 桌上下注的钱入池
	 */
	public void InBonusPool0() {
		java.util.ArrayList<SeatChip> seatChipList = new java.util.ArrayList<SeatChip>();
		int seatId;
		UserGameEntity user;
		for (int i = 0; i < this.gameOverLen; i++) {
			seatId = this.gameOverSeats[i];
			user = gameOverUsers[seatId - 1];
			if (user.seatChip > 0) {
				//如果在如池，玩家已经离开，
				seatChipList.add(new SeatChip(user, user.seatChip));
			}
		}
		Collections.sort(seatChipList);
		float chip;
		int size;
		boolean allin = false;
		float singleTotal = 0;
		SeatChip curSeatChip;
		while (seatChipList.size() > 0) {
			float baseChip = seatChipList.get(0).chip - singleTotal;
			singleTotal += baseChip;
			size = seatChipList.size();
			for (int i = 0; i < size; i++) {
				curSeatChip = seatChipList.get(i);
				chip = curSeatChip.chip;
				chip = chip - singleTotal;
				this.BonusPools[this.curBonusIndex] += baseChip;
				putBonus(curBonusIndex, curSeatChip.user.seatId);
				// 最后一个边池出现allin,下次计算要从新的边池开始
				if (seatChipList.size() == 1 && curSeatChip.user.user.stake <= 0) {
					Log.debug("最后一个边池出现allin,新的边池形成");
					allin = true;
				}
				if (chip == 0) {
					seatChipList.remove(i);
					// Log.debug("移除了减为0的一项，当前长度:" + seatChipList.size());
					i--;
					size--;
				}
			}
			//			Log.debug("第边" + (curBonusIndex + 1) + "池形成,总额:" + this.BonusPools[curBonusIndex] + " 当前桌上筹码长度:" + seatChipList.size());
			if (baseChip > 0 && seatChipList.size() > 0) {
				curBonusIndex++;
			}
		}
		StringBuilder sb = new StringBuilder("奖池已形成:");
		for (int i = 1; i <= this.BonusPools.length; i++) {
			if (this.BonusPools[i - 1] <= 0) {
				break;
			}
			sb.append(i + ":" + this.BonusPools[i - 1] + " ;");
		}
		Log.info(sb.toString());
		if (allin) {
			curBonusIndex++;
		}
	}

	private void putBonus(int bonusIndex, int seatId) {
		gameOverUsers[seatId - 1].bonusIndex = bonusIndex;
		//		if (!seatBonusMap.get(bonusIndex).contains(user)) {
		//			seatBonusMap.get(bonusIndex).add(user);
		//		}
	}

	public void AddBonusPool() {
		curBonusIndex++;
		Log.debug("有人all in,奖池数为:" + BonusPoolsSize());
	}

	public int BonusPoolsSize() {
		return curBonusIndex + 1;
	}

	public void clearBonusPool() {
		for (int i = 0; i < BonusPools.length; i++) {
			BonusPools[i] = 0;
			SystemWinPools[i] = 0;
		}
		Cornucopias.clear();
		addCornucopiaSuc = false;
		Log.debug("游戏重新开始，奖池清空");
	}

	/**
	 * 是否洗牌到积宝，防止洗牌再次出积宝,一交换请求段只出一个
	 */
	public boolean isGenerateCornucopia = false;
	// 积宝控制
	/**
	 * 中心服务器告诉游戏服务器下把是否可以出积宝
	 */
	public boolean isAllowCornucopia = false;
	/**
	 * 游戏当局有没有正在使用积宝指标
	 */
	public boolean isUsingCornucopia = false;
	/**
	 * 游戏服务器告诉中心服务器积宝有没有发出去
	 */
	public boolean isCornucopiaSend = false;
	/**
	 * 洗牌到积宝时候积宝牌型
	 */
	public int cornucopiaCardType;
	/**
	 * 洗牌到积宝时候玩家id
	 */
	public int cornucopiaUserId;
	public int cornucopiaidx;
	/**
	 * 当前积宝标识，中心服务器返回的
	 */
	public String cornucopiaCallBack;
	/**
	 * 洗牌到积宝时候坐位id
	 */
	public int cornucopiaSeatId;
	public UserGameEntity jackPotUser;

	public void CalculateWinner(int dbIndex) {
		// 计算牌型,所有玩家中，最大的手牌
		int seatId;
		UserGameEntity user;
		for (int i = 0; i < this.gameOverLen; i++) {
			seatId = this.gameOverSeats[i];
			user = gameOverUsers[seatId - 1];
			if (user.user != null && user.lastAction != LastAction.FOLD)
				user.calculateCard();
		}

		if (foldCount >= this.gameOverLen - 1) {
			boolShowCard = false;
		}
		// 计算每个边池的赢家, 分配边池，系统抽成
		int potLen = BonusPoolsSize();
		for (int i = 0; i < potLen; i++) {
			if (this.BonusPools[i] > 0)
				compareCard(i);
		}
		if (this.isAllowCornucopia && this.isUsingCornucopia) {
			Log.info("计算积宝赢家.cornucopiaCallBack:" + this.cornucopiaCallBack + " cornucopiaSeatId:" + cornucopiaSeatId + " cornucopiaCardType:" + cornucopiaCardType + " cornucopiaUserId:" + cornucopiaUserId);
			user = gameOverUsers[cornucopiaSeatId - 1];
		}
		// 判断是否产生聚宝盆
		jackPotUser = null;
		for (int i = 0; i < this.gameOverLen; i++) {
			seatId = this.gameOverSeats[i];
			user = gameOverUsers[seatId - 1];
			if (user == null || user.lastAction == LastAction.FOLD)
				continue;
			boolean isCornucopia = false;
			switch (user.cardType()) {
			case 9:
				isCornucopia = true;
				break;
			case 8:
				isCornucopia = true;
				break;
			case 7:
				isCornucopia = true;
				break;
			default:
				continue;
			}
			if (isCornucopia) {
				if (user.seatId != this.cornucopiaSeatId)
					throw new IllegalArgumentException("发的积宝牌不是指定位置");
			}
		}
		// 这里只保存基础数据
//		if (this.Cornucopias.size() > 1) {
//			throw new IllegalArgumentException("同一把游戏产生了好几个积宝，一个积宝回调只能是一个");
//		}
		if (this.isAllowCornucopia && this.isUsingCornucopia) {
			jackPotUser = this.gameOverUsers[this.cornucopiaSeatId - 1];
//			if (this.boolShowCard) {
			if (jackPotUser.lastAction != LastAction.FOLD) {
				GameServer.requestor.requestSendCornucopia(true, cornucopiaCallBack, cornucopiaCardType, this.RoomId, cornucopiaSeatId, jackPotUser.user.userId, jackPotUser.user.AccountId, jackPotUser.user.nickName, jackPotUser.getMaxCards());
			} else {
				GameServer.requestor.requestSendCornucopia(false, cornucopiaCallBack, cornucopiaCardType, this.RoomId, cornucopiaSeatId, jackPotUser.user.userId, jackPotUser.user.AccountId, jackPotUser.user.nickName, jackPotUser.getMaxCards());
			}
		} else {
//			if (this.Cornucopias.size() > 0)
//				throw new IllegalArgumentException("积宝不应该在此局出现!");
		}

		// 保存分成记录,边池，系统抽成,赢的玩家，玩家赢的钱
		GameRoomDaoImpl gameDao = GamePool.gameRoomDao(dbIndex);
		gameDao.UpdateBonusPools(this);
		// 保存结果,更新用户表
		// ??玩家退了	
		float win;
		for (int i = 0; i < this.gameOverLen; i++) {
			seatId = this.gameOverSeats[i];
			user = gameOverUsers[seatId - 1];
			win = user.totalWin - user.totalBet;
			if (!gameDao.saveGameWinner(this, this.RoomId, this.GameId, user.seatId, user.user, win, user.user.userName + "游戏赢了" + win)) {
				Log.error("游戏结束，保存结果失败!");
			}
			gameDao.addPlayMoneyLog(this, "sp_AddPlayMoneyLog", DBMgr.TexasPokerDB, user.user.userId, user.user.AccountId, 0, win, user.user.stake);

		}
	}

	public UserGameEntity[] BonusWinner(int bonusIndex) {
		return this.winnerMap[bonusIndex];
	}

	public void addAllWinner(UserGameEntity user) {
		try {
			if (allWinners[user.seatId - 1] != user) {
				allWinners[user.seatId - 1] = user;
				allWinnersLen++;
			}
		} catch (Exception e) {
			Log.error(e);
			e.printStackTrace();
		}

	}

	/**
	 * 从游戏结束快照里取
	 * 
	 * @return
	 */
	private UserGameEntity getFlodWinner() {
		int count = 0;
		UserGameEntity winner = null;
		int seatId;
		UserGameEntity temp;
		for (int i = 0; i < this.gameOverLen; i++) {
			seatId = this.gameOverSeats[i];
			temp = gameOverUsers[seatId - 1];
			if (temp.user != null && temp.lastAction != LastAction.FOLD) {
				count++;
				winner = temp;
			}
		}
		if (count != 1) {
			throw new IllegalArgumentException("不show牌型,只能一个人获胜！room:" + this.RoomCode + " game:" + this.GameId + " fold," + this.foldCount + "allin," + this.allinCount + " gameuser:" + this.gameUsers.size() + " count," + count);
		}
		return winner;
	}

	public void compareCard(int bonusIndex) {
		UserGameEntity[] winner = this.winnerMap[bonusIndex];
		winnerMapLen[bonusIndex] = 0;
		int seatId;
		UserGameEntity user;
		if (this.boolShowCard) {
			//没有排序比较前
			for (int i = 0; i < this.gameOverLen; i++) {
				seatId = this.gameOverSeats[i];
				user = gameOverUsers[seatId - 1];
				if (user.user == null || user.lastAction == LastAction.FOLD)
					continue;
				if (user.bonusIndex >= bonusIndex)
					winner[winnerMapLen[bonusIndex]++] = user;
			}
			//排序比较后
			//计算每边池赢家
			CalculateCard.calculateWinMap(this, bonusIndex);
			for (int i = 0; i < winnerMapLen[bonusIndex]; i++) {
				addAllWinner(winner[i]);
			}
		} else {
			//只取剩下的那个人
			winner[winnerMapLen[bonusIndex]++] = getFlodWinner();
			addAllWinner(winner[0]);
		}
		if (winnerMapLen[bonusIndex] < 1)
			throw new IllegalArgumentException("赢家数不能为0,gameid:" + this.GameId + ",bonusIndex:" + bonusIndex);
		//将计算输赢
		float winChip = Math.round((this.BonusPools[bonusIndex] * (1 - GameData.getFloat("SystemWinRate"))) / winnerMapLen[bonusIndex]);
		SystemWinPools[bonusIndex] = this.BonusPools[bonusIndex] - winnerMapLen[bonusIndex] * winChip;
		for (int i = 0; i < winnerMapLen[bonusIndex]; i++) {
			user = winner[i];
			user.user.stake += winChip;
			user.isWin = 1;
			user.totalWin += winChip;
			user.bonusWin[bonusIndex] = winChip;
		}
	}

	/**
	 * 一个边池里的玩家，比较其在对应该边池胜出与否
	 * 
	 * @param seatBonusUser
	 */
	private void compareCard0(int bonusIndex) {
		UserGameEntity user;
		//这里操作的只是9个列表中的数，减少了new的出现
		UserGameEntity[] winner = this.winnerMap[bonusIndex];
		//		Iterator<UserGameEntity> it = null;
		winnerMapLen[bonusIndex] = 0;
		if (this.boolShowCard) {
			//			java.util.ArrayList<UserInfoEntity> seatBonusUser = seatBonusMap.get(bonusIndex);
			//			if (seatBonusUser.size() < 1)
			//				it = seatBonusUser.iterator();
			// 计算获胜边池玩家
			// 得到所有玩家中，最大的手牌
			java.util.ArrayList<UserGameEntity> sortWinner = new java.util.ArrayList<UserGameEntity>();
			for (int i = 0; i < 9; i++) {
				if (gameOverUsers[i].user != null && gameOverUsers[i].bonusIndex >= bonusIndex && gameOverUsers[i].lastAction != LastAction.FOLD)
					sortWinner.add(gameOverUsers[i]);
				// 玩家虽然在边池下过注，但是没有等到游戏结束就离开了,排除
				//				if (user == null && !gameOverUsers.contains(user))
				//					continue;
				//				if (user.lastAction != LastAction.FOLD/* && user.roomId == this.RoomId && this.gameUsers.contains(user)*/) {
				//					sortWinner.add(user);
				//				} else {
				//					Log.debug("玩家放弃,失去了分配奖池" + user.nickName);
				//				}
			}
			if (sortWinner.size() < 1) {
				throw new IllegalArgumentException("游戏结束,每个边池必须有赢家1个,room:" + this.RoomId + " game" + this.GameId);
				//					Log.error("分钱的时候都跑光了，这钱系统要了");
				//					SystemWinPools[bonusIndex] = this.BonusPools[bonusIndex];
				//					// 存档
				//					return null;
			}
			Collections.sort(sortWinner);
			//				Log.debug("在以下玩家里选取赢家，排序后为:");
			//				for (int i = 0; i < sortWinner.size(); i++) {
			//					Log.debug(sortWinner.get(i).toString());
			//				}
			UserGameEntity nextUser;
			int result;
			//			winner.add(sortWinner.get(0));
			winner[winnerMapLen[bonusIndex]++] = sortWinner.get(0);
			addAllWinner(sortWinner.get(0));
			for (int i = 0; i < sortWinner.size(); i++) {
				user = sortWinner.get(i);
				if (i >= sortWinner.size() - 1) {
					break;
				} else {
					nextUser = sortWinner.get(i + 1);
				}
				//					Log.debug("排序 前type:" + user.cardType() + " 后type:" + nextUser.cardType());
				if (user.cardType() > nextUser.cardType()) {
					// winner.add(user);
					break;
				} else {
					result = user.isMoreThan(nextUser);
					if (result == 0) {
						//						winner.add(nextUser);
						winner[winnerMapLen[bonusIndex]++] = nextUser;
						addAllWinner(nextUser);
						i++;
					} else {
						// winner.add(user);
						break;
					}
				}

			}
		} else {
			winner[winnerMapLen[bonusIndex]++] = getFlodWinner();
			addAllWinner(winner[0]);
			//			winner.add(getFlodWinner());
			//			addAllWinner(winner.get(0));
		}
		// 把边池的钱加到玩家身上,防止小数点
		float winChip = Math.round((this.BonusPools[bonusIndex] * (1 - GameData.getFloat("SystemWinRate"))) / winnerMapLen[bonusIndex]);
		SystemWinPools[bonusIndex] = this.BonusPools[bonusIndex] - winnerMapLen[bonusIndex] * winChip;
		// user seat 0 error
		if (!this.boolShowCard) {
			if (winnerMapLen[bonusIndex] != 1) {
				throw new IllegalArgumentException("不show牌，赢家一定是1个");
			}

		}
		for (int i = 0; i < winnerMapLen[bonusIndex]; i++) {
			user = winner[i];
			user.user.stake += winChip;
			user.isWin = 1;
			user.totalWin += winChip;
			// 强制退了所有玩家.这里坐位id变成0，index -1 error
			//				seatTotalWinChips[user.gameOverSeatId - 1] += winChip;
			// Log.debug(String.format("玩家赢了%s,增多到%s", winChip,
			// user.stake));
			user.bonusWin[bonusIndex] = winChip;
		}

	}

	//	public int[] userBonus = new int[9];// 存产生边池AllIn时候,的钱如{100,100,100}
	public int[][] Winners = new int[9][9];// 边池玩家二维数组
	//	public java.util.ArrayList<WinCardEntity> winCards = new java.util.ArrayList<WinCardEntity>();
	//
	//	public int winCardsSize() {
	//		return winCards.size();
	//	}

	//	public Map<Integer, java.util.ArrayList<UserGameEntity>> winnerMap = new HashMap<Integer, java.util.ArrayList<UserGameEntity>>();
	public UserGameEntity[][] winnerMap = new UserGameEntity[9][9];
	public byte[] winnerMapLen = new byte[9];
	//	public java.util.ArrayList<UserGameEntity> allWinners = new java.util.ArrayList<UserGameEntity>();
	public UserGameEntity[] allWinners = new UserGameEntity[9];
	public byte allWinnersLen;

	public int getSeatUserId(int seatId) {
		if (seatId > 0 && seatId < 10) {
			if (gameOverUsers[seatId - 1].user != null)
				return gameOverUsers[seatId - 1].user.userId;
			//			if (seatUsers[seatId - 1] != null) {
			//				return seatUsers[seatId - 1].getUser().userId;
			//			}
		}
		return 0;
	}

	public int getSeatAcountId(int seatId) {
		if (seatId > 0 && seatId < 10) {
			if (gameOverUsers[seatId - 1].user != null)
				return gameOverUsers[seatId - 1].user.AccountId;
			//			if (seatUsers[seatId - 1] != null) {
			//				return seatUsers[seatId - 1].getUser().AccountId;
			//			}
		}
		return 0;
	}

	public String getHandCard(int seatId) {
		if (seatId > 0 && seatId < 10) {
			if (seatUsers[seatId - 1] != null) {
				return seatUsers[seatId - 1].getUser().card1 + "|" + seatUsers[seatId - 1].getUser().card2;
			}
		}
		return "";
	}

	@Override
	public String toString() {
		return String.format("GameId:%s,ServerId:%s,RoomId:%s,RoomName:%s,先前一局prevId:%s,GameState:%s,玩家数PlayerNum:%s,游戏桌总坐位SeatCount:%s", GameId, ServerId, RoomId, RoomName, prevId, GameState, PlayerNum, SeatCount);
	}

	//	public String getpublicCardInfo() {
	//		return String.format("五张公共牌:%s,%s,%s,%s,%s", PublicCard[0], PublicCard[1], PublicCard[2], PublicCard[3], PublicCard[4]);
	//	}

	public String getpublicCard() {
		return PublicCard[0] + "," + PublicCard[1] + "," + PublicCard[2] + "," + PublicCard[3] + "," + PublicCard[4];
		//		return String.format("%s|%s|%s|%s|%s", PublicCard[0], PublicCard[1], PublicCard[2], PublicCard[3], PublicCard[4]);
	}

	//	public String getBonusPoolsInfo() {
	//		String BonusPoolsInfo = "当前奖池状况:奖池1:" + BonusPools[0];
	//		for (int i = 1; i < BonusPools.length; i++) {
	//			if (BonusPools[i] > 0) {
	//				BonusPoolsInfo += "奖池" + (i + 1) + ":" + BonusPools[i] + ",";
	//			} else {
	//				break;
	//			}
	//		}
	//		return BonusPoolsInfo;
	//	}

	public void chipToBonus() {

	}

	public int getDealerId() {
		return DealerId;
	}

	public void setDealerId(int dealerId) {
		if (dealerId == 0) {
			Log.debug("庄家id不能为0");
		}
		//		Log.debug("设置庄家:" + dealerId);
		DealerId = dealerId;
	}
}

/**
 * 每次清除桌面的筹码之前，线计算每个人下注,同时生成池-user的关系
 * 
 * @author long
 * @date 2012-11-4 下午5:28:53
 * @qq 108232706
 * @description SeatChip
 */
class SeatChip implements Comparable<SeatChip> {
	public float chip;
	public UserGameEntity user;

	public SeatChip(UserGameEntity _user, float _chip) {
		this.user = _user;
		this.chip = _chip;
	}

	public int compareTo(SeatChip o) {
		if (o instanceof SeatChip) {
			return chip > o.chip ? 1 : -1;
		}
		return 0;
	}
}